package com.spzx.payment.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.DateUtils;
import com.spzx.order.api.RemoteOrderInfoService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spzx.payment.mapper.PaymentInfoMapper;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IPaymentInfoService;

/**
 * 付款信息Service业务层处理
 *
 * @author atguigu
 * @date 2025-04-03
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements IPaymentInfoService {

    @Autowired
    private RemoteOrderInfoService remoteOrderInfoService;

    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {
        //判断当前订单的paymentInfo是否存在
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = baseMapper.selectOne(queryWrapper);
        if (paymentInfo != null) {
            return paymentInfo;
        }

        //根据订单号获取订单
        R<OrderInfo> orderInfoResult = remoteOrderInfoService.getByOrderNo(orderNo, SecurityConstants.INNER);
        if (R.FAIL == orderInfoResult.getCode()) {
            throw new ServiceException(orderInfoResult.getMsg());
        }
        OrderInfo orderInfo = orderInfoResult.getData();

        //如果paymentInfo等于null
        paymentInfo = new PaymentInfo();
        //用户id
        paymentInfo.setUserId(orderInfo.getUserId());
        List<OrderItem> orderItemList = orderInfo.getOrderItemList();
//        orderItemList.stream().map(orderItem -> {
//            return orderItem.getSkuName();
//        }).collect(Collectors.joining(" "));
        //简写形式
        String content = orderItemList.stream()
                .map(OrderItem::getSkuName)
                .collect(Collectors.joining(" "));
        //支付内容
        paymentInfo.setContent(content);
        //总金额
        paymentInfo.setAmount(orderInfo.getTotalAmount());
        //1是微信，2是支付宝
        paymentInfo.setPayType(2);
        //商家订单号
        paymentInfo.setOrderNo(orderNo);
//        //支付订单号(暂时没有)
//        paymentInfo.setTradeNo("");
        //未支付，0为未支付，1为已支付，-1为关闭
        paymentInfo.setPaymentStatus(0);

        baseMapper.insert(paymentInfo);

        return paymentInfo;

    }

    @Override
    public void updatePaymentStatus(Map<String, String> paramMap, int paymentType) {
        //判断当前订单的paymentInfo是否存在
        LambdaQueryWrapper<PaymentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentInfo::getOrderNo, paramMap.get("out_trade_no"));
        PaymentInfo paymentInfo = baseMapper.selectOne(queryWrapper);
        //确保接口调用的幂等性，1为已支付
        if (paymentInfo != null && paymentInfo.getPaymentStatus() == 1) {
            return;
        }

        //更新支付日志
        //支付宝支付
        paymentInfo.setPayType(paymentType);
        //已支付
        paymentInfo.setPaymentStatus(1);
        //支付宝交易号
        paymentInfo.setTradeNo(paramMap.get("trade_no"));
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(JSON.toJSONString(paramMap));
        paymentInfo.setUpdateBy("支付宝回调");

        baseMapper.updateById(paymentInfo);

    }
}
